package com.product.android.ui.widget;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.common.android.utils.task.genericTask.GenericTask;
import com.common.android.utils.task.genericTask.TaskAdapter;
import com.common.android.utils.task.genericTask.TaskParams;
import com.common.android.utils.task.genericTask.TaskResult;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nd.android.u.allcommon.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.product.android.commonInterface.contact.RankFilterInfo;
import com.product.android.commonInterface.contact.RankFilterInfo.TimeCondition;
import com.product.android.commonInterface.contact.RankInfo;
import com.product.android.ui.adapter.TopRankListViewAdapter;
import com.product.android.utils.TimeUtils;

/**
 * 暗恋榜、鲜花榜VIEW
 * 
 * @author Huang YX
 * 
 */
public abstract class TopRankView extends LinearLayout implements
		OnRefreshListener<ListView>, OnLastItemVisibleListener {

	private Context mContext;
	private ProgressBar mPbLoad;
	private TextView mTvTip;
	private GenericTask mGetTask;
	private TopTaskListener mGetTaskListener;
	private PullToRefreshListView mListView;
	private TopRankListViewAdapter mAdapter;
	private View mFooterView;
	private TextView mTvTimeTip;

	// 当前筛选条件
	private RankFilterInfo mFilter = new RankFilterInfo();;

	// 获取更多线程是否在运行
	private boolean mIsGetMoreRunning = false;

	// 获取最新线程是否在运行
	private boolean mIsGetNewRunning = false;

	// 分批取当前取到多少页了
	private int mCurrentPage = 0;

	private int mRankType = 0;
	private int mScreenWidth;

	public static final int FLOWER_RANK = 0;
	public static final int SECRETLOVE_RANK = 1;
	public static final int SENDFLOWERTOME_RANK = 2;

	// 计时器，用来隐藏时间提示
	private Timer mTimer = null;
	
	//隐藏时间提示的动作是否在运行
	private boolean mIsHideActionRunning = false;
	
	private TranslateAnimation mShowTimeTipAni;
	
	private TranslateAnimation mHideTimeTipAni;

	private ArrayList<RankInfo> mlistRank = new ArrayList<RankInfo>();
	
	private Handler mParentHandler;
	
	private long mUid = 0;
	
	//数据总个数通知界面消息
	public static final int MSG_TOTALCOUNT = 200;

	public TopRankView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		mContext = context;
	}

	public TopRankView(Context context, int rankType, int screenWidth) {
		super(context);
		// TODO Auto-generated constructor stub
		mContext = context;
		mRankType = rankType;
		mScreenWidth = screenWidth;
	}
	
	public void setUid(long uid){
	    mUid = uid;
	}

	public void init() {
		// TODO Auto-generated method stub
		LayoutInflater.from(mContext).inflate(R.layout.top_rank_view, this,
				true);
		mPbLoad = (ProgressBar) findViewById(R.id.pbload);
		mTvTip = (TextView) findViewById(R.id.tvtip);
		mListView = (PullToRefreshListView) findViewById(R.id.rlvlist);
		mFooterView = LayoutInflater.from(mContext).inflate(
				R.layout.list_view_footer, null);
		mListView.getRefreshableView().addFooterView(mFooterView, null, false);
		mAdapter = new TopRankListViewAdapter(mContext, mRankType, mScreenWidth);
		mListView.setAdapter(mAdapter);
		mTvTimeTip = (TextView) findViewById(R.id.tvtimetip);

		mListView.setOnRefreshListener(this);
		mListView.setOnLastItemVisibleListener(this);
		mListView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), 
				false, true, 
				new OnScrollListener() {
					@Override
					public void onScrollStateChanged(AbsListView view, int scrollState) {
						//有滚动情况下隐藏提示view
						if(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
							hideTimeTip();
						}
					}

					@Override
					public void onScroll(AbsListView view, int firstVisibleItem,
							int visibleItemCount, int totalItemCount) {
						// TODO Auto-generated method stub

					}
		}));
		
//		mListView.setOnScrollListener(new OnScrollListener() {
//
//			@Override
//			public void onScrollStateChanged(AbsListView view, int scrollState) {
//				// TODO Auto-generated method stub
//				//快速滑动中不下载头像
//				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
//					ImageLoader.getInstance().pause();
//				} else {
//					ImageLoader.getInstance().resume();
//				}
//				
//				//有滚动情况下隐藏提示view
//				if(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
//					hideTimeTip();
//				}
//			}
//
//			@Override
//			public void onScroll(AbsListView view, int firstVisibleItem,
//					int visibleItemCount, int totalItemCount) {
//				// TODO Auto-generated method stub
//
//			}
//		});
		startTask();
	}

	public void stopTask() {
		if (mGetTask != null
				&& mGetTask.getStatus() == GenericTask.Status.RUNNING) {
			mGetTask.cancel(true);
		}
	}

	public void startTask() {
		stopTask();
		mGetTask = new GetTopTask();
		mGetTaskListener = new TopTaskListener();
		mGetTask.setListener(mGetTaskListener);
		mGetTask.execute(new TaskParams());
	}

	public void onDestroy() {
		stopTask();
		StopTimer();
		mlistRank.clear();
	}

	public ArrayList<RankInfo> mTempListRank;
	public int mTotalFlower;

	private class GetTopTask extends GenericTask {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			// TODO Auto-generated method stub
			return getData();
		}
	}
	
	private TaskResult getData(){
		TaskResult result = TaskResult.FAILED;
//		NdWeiboManager manager = NdWeiboManager.getInstance(mContext);
		int rank_min = 1;
		int pos = 0;
		if (mCurrentPage != 0){
			int currentSize = mlistRank.size();
			//取第一页时值为1，否则为列表的最后个排行值加1
			rank_min = currentSize == 0 ? 1 : mlistRank.get(
					currentSize - 1).ranking + 1;
			pos = currentSize;
		}
		try {
			switch(mRankType){
			case FLOWER_RANK:
			case SECRETLOVE_RANK:
				mTempListRank = getRankList(
						mFilter.getTimeSelect(), mFilter.getDepartid(),
						mFilter.getGenderSelect(), 30, rank_min, 0);
				break;
			case SENDFLOWERTOME_RANK:
				mTempListRank = new ArrayList<RankInfo>();
				mTotalFlower = getSendFlowerToMeList(mUid, 0, pos, mTempListRank, "1");
				break;
			}
			result = TaskResult.OK;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return result;
	}
	
	/**
	 * 获取排行榜数据
	 * @n<b>函数名称</b>     :getRankList
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param history
	 * @param  @param departid
	 * @param  @param gender
	 * @param  @param pageSize
	 * @param  @param rank_min
	 * @param  @param rank_max
	 * @param  @return
	 * @return ArrayList<RankInfo>
	 * @<b>作者</b>          :  黄永鑫
	 * @<b>创建时间</b>      :  2014-2-14上午11:04:56
	 */
	protected abstract ArrayList<RankInfo> getRankList(int history, long departid,
			int gender, int pageSize, int rank_min, int rank_max);
	
	/**
	 * 获取送给我的鲜花数据
	 * @n<b>函数名称</b>     :getSendFlowerToMeList
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param uid
	 * @param  @param isfuid
	 * @param  @param pos
	 * @param  @param listUser
	 * @param  @param order
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  黄永鑫
	 * @<b>创建时间</b>      :  2014-2-14上午11:05:48
	 */
	protected abstract int getSendFlowerToMeList(long uid, int isfuid, int pos,
			ArrayList<RankInfo> listUser, String order);

	private class TopTaskListener extends TaskAdapter {

		@Override
		public void onPreExecute(GenericTask task) {
			// TODO Auto-generated method stub
			if (mCurrentPage == 0) {
				mIsGetNewRunning = true;
			} else {
				mIsGetMoreRunning = true;
			}
			super.onPreExecute(task);
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			// TODO Auto-generated method stub
			mIsGetMoreRunning = false;
			mIsGetNewRunning = false;
			if (mCurrentPage == 0) {
				mListView.onRefreshComplete();
			} else {
				mFooterView.setVisibility(View.GONE);
			}
			if (result == TaskResult.OK) {
				// 展示数据
				if (mTempListRank != null) {
					if (mCurrentPage == 0){
						mlistRank.clear();
						if(mParentHandler != null){
							Message msg = mParentHandler.obtainMessage();
							msg.what = MSG_TOTALCOUNT;
							msg.arg1 = mTotalFlower;
							mParentHandler.sendMessage(msg);
						}
					}
					if(mTempListRank.size() > 0){
					    mlistRank.addAll(mTempListRank);
	                    mAdapter.setRankInfos(mlistRank);
	                    mAdapter.notifyDataSetChanged();
					}
				}
				showData();
				++mCurrentPage;
			} else {
				//获取失败
				if (mCurrentPage == 0) {
					mListView.setVisibility(View.GONE);
					mTvTip.setVisibility(View.VISIBLE);
					mPbLoad.setVisibility(View.GONE);
					mTvTip.setText(mContext.getString(R.string.get_fail));
				} else {
					Toast.makeText(mContext,
							mContext.getString(R.string.get_fail),
							Toast.LENGTH_LONG).show();
				}
			}
			super.onPostExecute(task, result);
		}

	}

	public void showData() {
		if (mlistRank.size() == 0) {
			mListView.setVisibility(View.GONE);
			mTvTip.setVisibility(View.VISIBLE);
			mPbLoad.setVisibility(View.GONE);
			mTvTip.setText(mContext.getString(R.string.no_data_now));
		} else {
			mListView.setVisibility(View.VISIBLE);
			mTvTip.setVisibility(View.GONE);
			mPbLoad.setVisibility(View.GONE);

			if (mCurrentPage == 0) {
				mAdapter.setRankInfos(mlistRank);
				mListView.setAdapter(mAdapter);
				// 如果是上周的要显示提示
				if (mFilter.getTimeSelect() == TimeCondition.LAST_WEEK) {
					showTimeTip();
				}
			}
		}
	}

	public void showTimeTip() {
		if(mShowTimeTipAni == null){
			mShowTimeTipAni = new TranslateAnimation(0, 0, -100f, 0);
			mShowTimeTipAni.setDuration(1000);
			mShowTimeTipAni.setFillAfter(true);
			mShowTimeTipAni.setAnimationListener(mShowAniListener);
		}
		
		mTvTimeTip.setText(mContext.getString(R.string.week_leaderboard)
				+ TimeUtils.getLastWeekStr());
		mTvTimeTip.startAnimation(mShowTimeTipAni);
	}
	
	/**
	 * 显示动画监听器
	 */
	private AnimationListener mShowAniListener = new AnimationListener(){

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			// 启动计时器，2S后隐藏时间提示
			StartTimer();
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
			mTvTimeTip.setVisibility(View.VISIBLE);
		}

	};

	public void hideTimeTip() {
		if(mIsHideActionRunning || mTvTimeTip.getVisibility() == View.GONE)
			return;
		mIsHideActionRunning = true;
		StopTimer();
		if(mHideTimeTipAni == null){
			mHideTimeTipAni = new TranslateAnimation(0, 0, 0, -100f);
			mHideTimeTipAni.setDuration(1000);
			mHideTimeTipAni.setFillAfter(true);
			mHideTimeTipAni.setAnimationListener(mHideAniListener);
		}
		mTvTimeTip.startAnimation(mHideTimeTipAni);
	}
	
	/**
	 * 隐藏动画监听器
	 */
	private AnimationListener mHideAniListener = new AnimationListener(){

		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			mIsHideActionRunning = false;
			mTvTimeTip.setVisibility(View.GONE);
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
		}
	}; 

	/**
	 * 重新设置过滤条件
	 * 
	 * @param filter
	 */
	public void setFilter(RankFilterInfo filter) {
		mFilter = filter;
		mListView.setVisibility(View.GONE);
		mTvTip.setVisibility(View.GONE);
		mPbLoad.setVisibility(View.VISIBLE);
		mCurrentPage = 0;
		startTask();
	}

	public RankFilterInfo getFilter() {
		return mFilter;
	}

	@Override
	public void onLastItemVisible() {
		// TODO Auto-generated method stub
		// 正在刷新中时不取更多
		if (mIsGetNewRunning) {
			Toast.makeText(mContext,
					mContext.getString(R.string.refreshing_please_wait),
					Toast.LENGTH_LONG).show();
			return;
		}

		if (mIsGetMoreRunning) {
			return;
		}

		mFooterView.setVisibility(View.VISIBLE);
		startTask();
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		// 如果正在取更多则不刷新
		if (mIsGetMoreRunning) {
			mListView.onRefreshComplete();
			Toast.makeText(mContext,
					mContext.getString(R.string.gettingmore_please_wait),
					Toast.LENGTH_LONG).show();
			return;
		}

		if (mIsGetNewRunning) {
			return;
		}

		mCurrentPage = 0;
		startTask();
	}

	/**
	 * 停止计时器
	 */
	private void StopTimer() {
		if (mTimer != null) {
			mTimer.purge();
			mTimer.cancel();
		}
	}

	/**
	 * 开始计时器
	 */
	private void StartTimer() {
		StopTimer();
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(MSG_HIDETIMETIP);
			}
		}, 2000, 1);
	}

	public final int MSG_HIDETIMETIP = 100;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_HIDETIMETIP:
				hideTimeTip();
				break;
			}

		}

	};
	
	/**
	 * 设置时间类型
	 * @param timeSelect
	 */
    public void setTimeSelect(int timeSelect){
		mFilter.setTimeSelect(timeSelect);
	}
    
    /**
     * 设置性别类型
     * @param genderSelect
     */
    public void setGender(int genderSelect){
    	mFilter.setGenderSelect(genderSelect);
    }
    
    /**
     * 刷新界面，主要为了刷新头像
     */
    public void refresh(){
    	if(mAdapter != null)
    		mAdapter.notifyDataSetChanged();
    }
    
    public void setParentHanlder(Handler parHandler){
    	mParentHandler = parHandler;
    }

    public boolean isInit() {
        return mlistRank == null ? false : true;
    }


}
